/*
* @Author: An
* @Date:   2017-07-08 11:36:19
* @Last Modified by:   An
* @Last Modified time: 2017-07-08 13:52:38
*/

'use strict';
require('./index.css');
require('page/common/nav-simple/index.css');
var _user = require('service/user-service.js');
var _xj = require('util/xj.js');

// 表单中的错误提示
var formError = {
	show : function(errMsg) {
		$('.error-item').show().find('.error-msg').text(errMsg);
	},
	hide : function() {
		$('.error-item').hide().find('.error-msg').text('');
	}
};

// 逻辑
var page = {
	init : function() {
		this.bindEvent();
	},
	bindEvent : function(){
		var _this = this;
		// 校验用户名
		$('#username').blur(function() {
			var username = $.trim($(this).val());
			// 如果用户名为空，不做校验
			if (!username) {
				return;
			}
			// 异步校验用户名是否存在
			_user.checkUsername(username, function(res) {
				formError.hide();
			}, function(errMsg) {
				formError.show(errMsg);
			});
		});
		// 注册按钮的点击
		$('#submit').click(function() {
			_this.submit();
		});
		// 如果按下回车键也进行提交
		$('.user-content').keyup(function(e) {
			if(e.keyCode === 13) {
				_this.submit();
			}
		});
	},
	// 提交表单
	submit : function() {
		var formData = {
			username 		: $.trim($('#username').val()),
			password 		: $.trim($('#password').val()),
			passwordConfirm : $.trim($('#password-confirm').val()),
			phone 			: $.trim($('#phone').val()),
			email 			: $.trim($('#email').val()),
			question 		: $.trim($('#question').val()),
			answer 			: $.trim($('#answer').val()),
		},
		// 表单校验结果
		validateResult = this.formValidate(formData);
		if(validateResult.status) {
			_user.register(formData, function(res) {
				window.location.href = './result.html?type=register';
			}, function(errMsg) {
				formError.show(errMsg);
			});
		} else {
			formError.show(validateResult.msg);
		}
	},
	// 表单字段的校验
	formValidate : function(formData) {
		var result = {
			status 	: false,
			msg 	: ''
		};
		if (!_xj.validate(formData.username, 'require')) {
			result.msg = '用户名不能为空';
			return result;
		}
		// 校验密码不能为空
		if (!_xj.validate(formData.password, 'require')) {
			result.msg = '密码不能为空';
			return result;
		}
		// 校验密码长度
		if (formData.password.length < 6) {
			result.msg = '密码长度不能少于6位';
			return result;
		}
		if (formData.password !== formData.passwordConfirm) {
			result.msg = '两次输入的密码不一致';
			return result;
		}
		if (!_xj.validate(formData.phone, 'phone')) {
			result.msg = '手机号格式不正确';
			return result;
		}
		if (!_xj.validate(formData.email, 'email')) {
			result.msg = '邮箱格式不正确';
			return result;
		}
		if (!_xj.validate(formData.question, 'require')) {
			result.msg = '密码提示问题不能为空';
			return result;
		}
		if (!_xj.validate(formData.answer, 'require')) {
			result.msg = '密码提示问题答案不能为空';
			return result;
		}
		// 通过验证，返回正确提示
		result.status = true;
		result.msg = '登录成功';
		return result;
	}
};
$(function(){
	page.init();
});